{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 从test.csv 和 train.csv中提取出event_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "uniqueEvent = set()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "for str in ['test.csv','train.csv']:\n",
    "    with open(str,'r') as f:\n",
    "        f.readline()\n",
    "        while True:\n",
    "            line = f.readline()\n",
    "            if not line:\n",
    "                break\n",
    "            content = line.split(',')\n",
    "            uniqueEvent.add(content[1])\n",
    "          "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "13418"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(uniqueEvent)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 抽取出只在训练集和测试集中出现的event,并把聚类要用到的特征放在selectEvent.csv中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with open('selectEvent.csv','w') as wf:\n",
    "    with open('events.csv','r') as f:\n",
    "        f.readline()\n",
    "        while True:\n",
    "            line = f.readline()\n",
    "            if not line:\n",
    "                break\n",
    "            content = line.split(',')\n",
    "            event_id = content[0]\n",
    "            if event_id in uniqueEvent:\n",
    "                feature = content[9:]\n",
    "                str1 = ','.join(feature)\n",
    "                wf.write(str1)\n",
    "            \n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 读取数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "train = pd.read_csv('selectEvent.csv',header=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 用密度函数进行聚类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.cluster import DBSCAN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn import metrics\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.metrics import silhouette_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "db = DBSCAN()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "labels = db.fit_predict(train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "silhouette_avg = silhouette_score(train, labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-0.472577746477\n"
     ]
    }
   ],
   "source": [
    "print(silhouette_avg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分数好低，可见用dbscan不合适"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 用K-Means进行聚类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For n_clusters = 2 The average silhouette_score is : 0.993903490063\n",
      "For n_clusters = 5 The average silhouette_score is : 0.583186639954\n",
      "For n_clusters = 10 The average silhouette_score is : 0.510087331132\n",
      "For n_clusters = 15 The average silhouette_score is : 0.407595930401\n"
     ]
    }
   ],
   "source": [
    "\n",
    "range_n_clusters = [2, 5, 10, 15]\n",
    "for n_clusters in range_n_clusters:\n",
    "    clusterer = KMeans(n_clusters=n_clusters,random_state = 10)\n",
    "    cluster_labels = clusterer.fit_predict(train)\n",
    "    silhouette_avg = silhouette_score(train, cluster_labels)\n",
    "    print(\"For n_clusters =\", n_clusters,\n",
    "          \"The average silhouette_score is :\", silhouette_avg)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "初调发现轮廓系数越来越小，可能最佳分类藏在 2 到 5 之间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For n_clusters = 2 The average silhouette_score is : 0.993903490063\n",
      "For n_clusters = 3 The average silhouette_score is : 0.736598334223\n",
      "For n_clusters = 4 The average silhouette_score is : 0.62631668377\n",
      "For n_clusters = 5 The average silhouette_score is : 0.583186639954\n"
     ]
    }
   ],
   "source": [
    "range_n_clusters = [2, 3, 4, 5]\n",
    "for n_clusters in range_n_clusters:\n",
    "    clusterer = KMeans(n_clusters=n_clusters,random_state=10)\n",
    "    cluster_labels = clusterer.fit_predict(train)\n",
    "    silhouette_avg = silhouette_score(train, cluster_labels)\n",
    "    print(\"For n_clusters =\", n_clusters,\n",
    "          \"The average silhouette_score is :\", silhouette_avg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可见分为2类是最好的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 用层次聚类算法进行聚类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For n_clusters = 2 The average silhouette_score is : 0.993903490063\n",
      "For n_clusters = 3 The average silhouette_score is : 0.732291959682\n",
      "For n_clusters = 4 The average silhouette_score is : 0.694269765833\n",
      "For n_clusters = 5 The average silhouette_score is : 0.447604267585\n"
     ]
    }
   ],
   "source": [
    "from sklearn.cluster import AgglomerativeClustering\n",
    "range_n_clusters = [2, 3, 4, 5]\n",
    "for n_clusters in range_n_clusters:\n",
    "    clusterer = AgglomerativeClustering(n_clusters=n_clusters)\n",
    "    cluster_labels = clusterer.fit_predict(train)\n",
    "    silhouette_avg = silhouette_score(train, cluster_labels)\n",
    "    print(\"For n_clusters =\", n_clusters,\n",
    "          \"The average silhouette_score is :\", silhouette_avg)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "依然是分为2类时最优秀"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
